/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Master;

import Core.ConnectionHandler;
import Core.IConnectionHandler;
import Core.IConnectionListener;
import Core.MessageBuilder;
import Core.MessageType;
import Message.GetSlaveMessage;
import Message.SlaveReportMessage;
import MessageHandler.IMessageHandler;
import Slave.SlaveInfo;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author Mr Bao
 */
public class MasterClient implements IConnectionListener {

    private Socket client;
    private MasterServer server;
    private IConnectionHandler connectionHandler;

    public MasterClient(MasterServer server, Socket client) throws IOException {
        this.server = server;
        this.client = client;
        this.connectionHandler = new ConnectionHandler(client, this);
        ((ConnectionHandler) this.connectionHandler).SetDispatcher(this.server.GetDispatcher());
        ((ConnectionHandler) this.connectionHandler).Init();
    }

    public void IncommingMessage(String message) {
        System.out.println("Message from client: " + message);
        if (message.startsWith(MessageType.SlaveReportMessage)) {
            SlaveReportMessage(message);
        } else if (message.startsWith(MessageType.GetSlaveMessage)) {
            GetSlaveMessage();
        }
    }

    private void SlaveReportMessage(String message) {
        IMessageHandler handler;
        handler = server.GetMessageHandler(SlaveReportMessage.class);
        SlaveInfo slaveInfo = (SlaveInfo) handler.Process(message, null);
        boolean isActive = server.TryGetValue(slaveInfo.getAddress(), slaveInfo.getPort());
        if (isActive) {
            server.UpdateSlaveInfo(slaveInfo.getId(), slaveInfo.getCurrentConnections());
        } else {
            server.AddSlaveInfo(slaveInfo);
        }
    }

    private void GetSlaveMessage() {
        SlaveInfo slaveInfo;
        try {
            slaveInfo = server.GetSlave();
            String message = MessageBuilder.BuildGetSlaveResultMessage(slaveInfo);
            ((ConnectionHandler) connectionHandler).QueueMessage(message);
        } catch (Exception e) {
        }
    }

    public void SocketClosed() {
        if (client != null && !client.isClosed()) {
            try {
                client.close();
            } catch (Exception e) {
            }
        }
    }
}
